/**
 * Copyright 2013 ABSir's Studio
 * 
 * All right reserved
 *
 * Create on 2013-6-14 下午4:26:47
 */
package com.absir.android.waps;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.TextView;
import cn.waps.AppConnect;
import cn.waps.UpdatePointsNotifier;

import com.absir.android.context.annotation.AfterCreate;
import com.absir.android.goods.GoodsContextUtils;
import com.absir.android.goods.IGoodsInfo;
import com.absir.android.view.StoreItemView;
import com.absir.android.view.annotation.InjectBinder;
import com.absir.android.view.annotation.InjectView;
import com.absir.android.view.listener.OnClick;
import com.absir.core.kernel.KernelDyna;
import com.absir.core.kernel.KernelString;
import com.wanpu.pay.PayConnect;
import com.wanpu.pay.PayResultListener;

/**
 * @author absir
 * 
 */
public class WapsStoreActivity extends Activity implements OnClickListener, UpdatePointsNotifier {

	/** points_button */
	@InjectView(binders = { @InjectBinder(listeners = { OnClick.class }, method = "points_buttonClick") })
	private Button points_button;

	/** historyPoints */
	private int historyPoints;

	/** points_text */
	@InjectView
	private TextView points_text;

	/** coin_text */
	@InjectView
	private TextView coin_text;

	/** gain_coin_text */
	@InjectView
	private TextView gain_coin_text;

	/** store_items_layout */
	@InjectView
	private ViewGroup store_items_layout;

	@AfterCreate
	protected void afterCreate() {
		PayConnect.getInstance("d89b69ae141c00d344a476d44d0569ed", "WAPS", this);
		if (store_items_layout != null) {
			int count = store_items_layout.getChildCount();
			View view = count > 0 ? store_items_layout.getChildAt(0) : null;
			if (view != null && view.getTag() != null && !KernelString.isEmpty(view.getTag().toString())) {
				for (int i = 0; i < count; i++) {
					view = store_items_layout.getChildAt(i);
					Integer coin = KernelDyna.to(view.getTag(), Integer.class);
					IGoodsInfo goodsInfo = coin == null ? GoodsContextUtils.getCoinGoodsDefine().getGoodsInfo(view.getTag()) : GoodsContextUtils.getCoinGoodsDefine().getGoodsInfo(coin);
					if (goodsInfo != null) {
						StoreItemView itemView = getItemView(goodsInfo);
						itemView.setContentView(view);
						itemView.setGoodsInfo(goodsInfo, this);
					}
				}

			} else {
				LayoutParams layoutParams = view == null ? null : view.getLayoutParams();
				store_items_layout.removeAllViews();
				for (IGoodsInfo goodsInfo : GoodsContextUtils.getCoinGoodsDefine().getGoodsInfos()) {
					StoreItemView itemView = getItemView(goodsInfo);
					store_items_layout.addView(itemView.getContentView());
					itemView.getContentView().setLayoutParams(layoutParams);
					itemView.setGoodsInfo(goodsInfo, this);
				}
			}
		}

		historyPoints = AppConnect.getHistoryPoints(this);
		AppConnect.getInstance(this).getPoints(this);
		update();
	}

	/**
	 * 
	 */
	protected void update() {
		updatePoints();
		updateCoin();
	}

	/**
	 * 
	 */
	protected void updatePoints() {
		if (points_text != null) {
			points_text.setText(String.valueOf(historyPoints));

		} else if (points_button != null) {
			points_button.setText(String.valueOf(historyPoints));
		}
	}

	/**
	 * 
	 */
	protected void updateCoin() {
		if (coin_text != null) {
			coin_text.setText(String.valueOf(GoodsContextUtils.getCoinGoodsDefine().getGoodsCoin()));
		}
	}

	/**
	 * 
	 */
	protected synchronized void points_buttonClick(View v) {
		final int avaibablePoints = getAvaibablePoints();
		if (avaibablePoints < 0) {
			needMorePoints();

		} else {
			AppConnect.getInstance(this).spendPoints(avaibablePoints, new UpdatePointsNotifier() {

				@Override
				public void getUpdatePointsFailed(String arg0) {
					// TODO Auto-generated method stub
					errorExchangePoints();
				}

				@Override
				public void getUpdatePoints(String arg0, int arg1) {
					// TODO Auto-generated method stub
					historyPoints -= arg1;
					GoodsContextUtils.getCoinGoodsDefine().gainGoodsCoin(getCoinPoints(arg1));
					update();
					successExchangePoinits(arg1);
				}
			});
		}
	}

	/**
	 * @return
	 */
	protected float getCoinPointsRate() {
		return 0.1f;
	}

	/**
	 * @return
	 */
	protected int getAvaibablePoints() {
		int coin = (int) (historyPoints * getCoinPointsRate());
		return (int) (coin / getCoinPointsRate());
	}

	/**
	 * @param points
	 * @return
	 */
	protected int getCoinPoints(int points) {
		return (int) (points * getCoinPointsRate());
	}

	/**
	 * 
	 */
	protected void needMorePoints() {
		new AlertDialog.Builder(this).setTitle("提示").setMessage("积分不足于兑换！").setPositiveButton("确定", null).show();
	}

	/**
	 * 
	 */
	protected void errorExchangePoints() {
		new AlertDialog.Builder(this).setTitle("提示").setMessage("兑换失败！").setPositiveButton("确定", null).show();
	}

	/**
	 * @param points
	 */
	protected void successExchangePoinits(int points) {
		new AlertDialog.Builder(this).setTitle("恭喜").setMessage("兑换成功！").setPositiveButton("确定", null).show();
	}

	/**
	 * @param goodsInfo
	 * @return
	 */
	protected StoreItemView getItemView(IGoodsInfo goodsInfo) {
		return new StoreItemView();
	}

	/**
	 * @return
	 */
	protected String getUserId() {
		return null;
	}

	/**
	 * @return
	 */
	protected String getNotifyUrl() {
		return null;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.view.View.OnClickListener#onClick(android.view.View)
	 */
	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		if (v.getTag() != null && v.getTag() instanceof StoreItemView) {
			final StoreItemView storeItemView = (StoreItemView) v.getTag();
			final IGoodsInfo goodsInfo = (IGoodsInfo) storeItemView.getTag();
			// // 游戏商自定义支付订单号，保证该订单号的唯一性，建议在执行支付操作时才进行该订单号的生成
			String orderId = System.currentTimeMillis() + "_" + goodsInfo.getTag();
			PayConnect.getInstance(this).pay(this, orderId, getUserId(), goodsInfo.getPrice(), goodsInfo.getGoodsName(), goodsInfo.getGoodsDesc(), getNotifyUrl(), new PayResultListener() {

				@Override
				public void onPayFinish(Context arg0, String orderId, int resultCode, String resultString, int payType, float amount, String goodsName) {
					// TODO Auto-generated method stub
					WapsStoreActivity.this.onPayFinish(storeItemView, goodsInfo, orderId, resultCode, resultString, payType, amount, goodsName);
				}

			});
		}
	}

	/**
	 * @param storeItemView
	 * @param goodsInfo
	 * @param orderId
	 * @param resultCode
	 * @param resultString
	 * @param payType
	 * @param amount
	 * @param goodsName
	 */
	public boolean onPayFinish(StoreItemView storeItemView, IGoodsInfo goodsInfo, String orderId, int resultCode, String resultString, int payType, float amount, String goodsName) {
		// TODO Auto-generated method stub
		if (GoodsContextUtils.getCoinGoodsDefine().gainGoodsInfo(goodsInfo.getTag(), 1)) {
			storeItemView.update();
			if (goodsInfo.getTag() instanceof Integer) {
				updateCoin();
			}
		}

		return false;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see cn.waps.UpdatePointsNotifier#getUpdatePoints(java.lang.String, int)
	 */
	@Override
	public void getUpdatePoints(String arg0, int arg1) {
		// TODO Auto-generated method stub
		if (historyPoints != arg1) {
			historyPoints = arg1;
			updatePoints();
		}
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see cn.waps.UpdatePointsNotifier#getUpdatePointsFailed(java.lang.String)
	 */
	@Override
	public void getUpdatePointsFailed(String arg0) {
		// TODO Auto-generated method stub
	}
}
